package com.itheima.api;

import com.itheima.domain.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.annotation.Resource;
import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi{

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 保存好友欢喜到表
     * @param id1
     * @param id2
     */
    @Override
    public void save(Long id1, Long id2) {

        //保存自己的
        Query query1 = Query.query(Criteria.where("userId").is(id1).and("frinedId").is(id2));
        if(mongoTemplate.exists(query1,Friend.class)) {
            Friend friend = new Friend();
            friend.setCreated(System.currentTimeMillis());
            friend.setUserId(id1);
            friend.setFriendId(id2);
            mongoTemplate.save(friend);
        }
        //保存朋友的
        Query query2 = Query.query(Criteria.where("userId").is(id2).and("frinedId").is(id1));
        if (mongoTemplate.exists(query2,Friend.class)){
            Friend friend2 = new Friend();
            friend2.setCreated(System.currentTimeMillis());
            friend2.setUserId(id2);
            friend2.setFriendId(id1);
            mongoTemplate.save(friend2);
        }
    }

    /**
     * 查询好友列表
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Friend> friendList(Long userId,Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId)).skip((long) (page - 1) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Friend.class);
    }

    /**
     * 删除好友
     */
    @Override
    public void delete(Long id1, Long id2) {
        Query query1 = Query.query(Criteria.where("userId").is(id1).and("frinedId").is(id2));
        if (mongoTemplate.exists(query1,Friend.class)){
            mongoTemplate.remove(query1);
        }
        Query query2 = Query.query(Criteria.where("userId").is(id2).and("frinedId").is(id1));
        if (mongoTemplate.exists(query2,Friend.class)){
            mongoTemplate.remove(query2);
        }
    }


}
